#!/usr/bin/python3
"""
Configure systemd-logind

The 'config' option allows to create a systemd-logind configuration
drop-in file in `/usr/lib/systemd/logind.conf.d` with the name
`filename`.

Drop-in configuration files can currently specify the following subset of
options:
  - 'Login' section
    - 'NAutoVTs' option

At least one option must be specified in the 'Login' section.
"""


import os
import sys
import configparser

import osbuild.api


SCHEMA = r"""
"additionalProperties": false,
"required": ["config", "filename"],
"properties": {
  "filename": {
    "type": "string",
    "description": "Name of the systemd-logind drop-in.",
    "pattern": "^[\\w.-]{1,250}\\.conf$"
  },
  "config": {
    "additionalProperties": false,
    "type": "object",
    "description": "systemd-logind configuration",
    "minProperties": 1,
    "properties": {
      "Login": {
        "additionalProperties": false,
        "type": "object",
        "description": "'Login' configuration section.",
        "minProperties": 1,
        "properties": {
          "NAutoVTs": {
            "type": "integer",
            "minimum": 0,
            "description": "Configures how many virtual terminals (VTs) to allocate by default."
          }
        }
      }
    }
  }
}
"""


def main(tree, options):
    dropin_file = options["filename"]
    dropin_config = options["config"]

    dropins_dir = f"{tree}/usr/lib/systemd/logind.conf.d"
    os.makedirs(dropins_dir, exist_ok=True)

    config = configparser.ConfigParser()
    # prevent conversion of the option name to lowercase
    config.optionxform = lambda option: option

    for section, opts in dropin_config.items():
        if not config.has_section(section):
            config.add_section(section)
        for option, value in opts.items():
            config.set(section, option, str(value))

    with open(f"{dropins_dir}/{dropin_file}", "w") as f:
        config.write(f, space_around_delimiters=False)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["tree"], args["options"])
    sys.exit(r)
